{% extends 'tasks/base.html' %}

{% block title %}
    {% if form.instance.id %}编辑任务{% else %}创建任务{% endif %}
{% endblock %}

{% block content %}
    <div class="card">
        <div class="card-header">
            <h1>{% if form.instance.id %}编辑任务{% else %}创建任务{% endif %}</h1>
        </div>
        <div class="card-body">
            <form method="post" novalidate enctype="multipart/form-data">
                {% csrf_token %}

                <h4 class="mt-3 mb-3 border-bottom pb-2">基本信息</h4>

                <div class="mb-3">
                    <label for="{{ form.title.id_for_label }}" class="form-label">标题</label>
                    <input type="text" class="form-control {% if form.title.errors %}is-invalid{% endif %}"
                           id="{{ form.title.id_for_label }}" name="{{ form.title.name }}"
                           value="{{ form.title.value|default:'' }}">
                    {% if form.title.errors %}
                        <div class="invalid-feedback">
                            {{ form.title.errors }}
                        </div>
                    {% endif %}
                </div>

                <div class="mb-3">
                    <label for="{{ form.description.id_for_label }}" class="form-label">描述</label>
                    <textarea class="form-control {% if form.description.errors %}is-invalid{% endif %}"
                              id="{{ form.description.id_for_label }}" name="{{ form.description.name }}"
                              rows="3">{{ form.description.value|default:'' }}</textarea>
                    {% if form.description.errors %}
                        <div class="invalid-feedback">
                            {{ form.description.errors }}
                        </div>
                    {% endif %}
                </div>

                <div class="mb-3">
                    <label for="{{ form.status.id_for_label }}" class="form-label">状态</label>
                    <select class="form-select {% if form.status.errors %}is-invalid{% endif %}"
                            id="{{ form.status.id_for_label }}" name="{{ form.status.name }}">
                        {% for value, text in form.status.field.choices %}
                            <option value="{{ value }}" {% if form.status.value == value %}selected{% endif %}>
                                {{ text }}
                            </option>
                        {% endfor %}
                    </select>
                    {% if form.status.errors %}
                        <div class="invalid-feedback">
                            {{ form.status.errors }}
                        </div>
                    {% endif %}
                </div>

                <h4 class="mt-4 mb-3 border-bottom pb-2">项目信息</h4>

                <div class="row mb-3">
                    <div class="col-md-6">
                        <label for="{{ form.Projectname.id_for_label }}" class="form-label">项目名称</label>
                        <input type="text" class="form-control {% if form.Projectname.errors %}is-invalid{% endif %}"
                               id="{{ form.Projectname.id_for_label }}" name="{{ form.Projectname.name }}"
                               value="{{ form.Projectname.value|default:'' }}">
                        {% if form.Projectname.errors %}
                            <div class="invalid-feedback">
                                {{ form.Projectname.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6">
                        <label for="{{ form.system.id_for_label }}" class="form-label">系统</label>
                        <input type="text" class="form-control {% if form.system.errors %}is-invalid{% endif %}"
                               id="{{ form.system.id_for_label }}" name="{{ form.system.name }}"
                               value="{{ form.system.value|default:'' }}">
                        {% if form.system.errors %}
                            <div class="invalid-feedback">
                                {{ form.system.errors }}
                            </div>
                        {% endif %}
                    </div>
                </div>

                <h4 class="mt-4 mb-3 border-bottom pb-2">人员角色</h4>

                <div class="row mb-3">
                    <div class=" col-md-6 ">
                        <label for="{{ form.ProjectManager.id_for_label }}" class="form-label">项目经理</label>
{#                        <button type="button" onclick="getProMan()">获取项目经理</button>#}
{#                        <select class=" form-select {% if form.ProjectManager.errors %}is-invalid{% endif %}"#}
{#                                 id="{{ form.ProjectManager.id_for_label }}" name="{{ form.ProjectManager.name }}">#}
{#                            <option  value=value="{{ form.ProjectManager.value|default:'' }}>-- 请选择 --</option>#}
{#                            {% for value, text in form.ProjectManager.field.choices %}#}
{#                                <option class="pro-data" value="{{ value }}"#}
{#                                        {% if form.ProjectManager.value|stringformat:"s" == value|stringformat:"s" %}selected{% endif %}>#}
{#                                    {{ text }}#}
{#                                </option>#}
{#                            {% endfor %}#}
{#                        </select>#}
                                                <input type="text"
                                                       class=" form-control {% if form.ProjectManager.errors %}is-invalid{% endif %}"
                                                       id="{{ form.ProjectManager.id_for_label }}" name="{{ form.ProjectManager.name }}"
                                                       value="{{ form.ProjectManager.value|default:'' }}">
                        {% if form.ProjectManager.errors %}
                            <div class=" invalid-feedback">
                                {{ form.ProjectManager.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6">
                        <label for="{{ form.ProductManager.id_for_label }}" class="form-label">产品经理</label>
                        <input type="text" class="form-control {% if form.ProductManager.errors %}is-invalid{% endif %}"
                               id="{{ form.ProductManager.id_for_label }}" name="{{ form.ProductManager.name }}"
                               value="{{ form.ProductManager.value|default:'' }}">
                        {% if form.ProductManager.errors %}
                            <div class="invalid-feedback">
                                {{ form.ProductManager.errors }}
                            </div>
                        {% endif %}
                    </div>
                </div>

                <div class="row mb-3">
                    <div class="col-md-6">
                        <label for="{{ form.DevelopmentEngineer.id_for_label }}" class="form-label">开发工程师</label>
                        <input type="text"
                               class="form-control {% if form.DevelopmentEngineer.errors %}is-invalid{% endif %}"
                               id="{{ form.DevelopmentEngineer.id_for_label }}"
                               name="{{ form.DevelopmentEngineer.name }}"
                               value="{{ form.DevelopmentEngineer.value|default:'' }}">
                        {% if form.DevelopmentEngineer.errors %}
                            <div class="invalid-feedback">
                                {{ form.DevelopmentEngineer.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6">
                        <label for="{{ form.TestEngineer.id_for_label }}" class="form-label">测试工程师</label>
                        <input type="text" class="form-control {% if form.TestEngineer.errors %}is-invalid{% endif %}"
                               id="{{ form.TestEngineer.id_for_label }}" name="{{ form.TestEngineer.name }}"
                               value="{{ form.TestEngineer.value|default:'' }}">
                        {% if form.TestEngineer.errors %}
                            <div class="invalid-feedback">
                                {{ form.TestEngineer.errors }}
                            </div>
                        {% endif %}
                    </div>
                </div>

                {% if user.is_authenticated %}
                    <div class="mb-3">
                        <label for="{{ form.assigned_to.id_for_label }}" class="form-label">分配给</label>
                        <select class="form-select {% if form.assigned_to.errors %}is-invalid{% endif %}"
                                id="{{ form.assigned_to.id_for_label }}" name="{{ form.assigned_to.name }}">
                            <option value="">-- 未分配 --</option>
                            {% for value, text in form.assigned_to.field.choices %}
                                <option value="{{ value }}"
                                        {% if form.assigned_to.value|stringformat:"s" == value|stringformat:"s" %}selected{% endif %}>
                                    {{ text }}
                                </option>
                            {% endfor %}
                        </select>
                        {% if form.assigned_to.errors %}
                            <div class="invalid-feedback">
                                {{ form.assigned_to.errors }}
                            </div>
                        {% endif %}
                    </div>
                {% endif %}

                <h4 class="mt-4 mb-3 border-bottom pb-2">链接</h4>

                <div class="row mb-3">
                    <div class="col-md-6">
                        <label for="{{ form.Demandlink.id_for_label }}" class="form-label">需求链接</label>
                        <input type="url" class="form-control {% if form.Demandlink.errors %}is-invalid{% endif %}"
                               id="{{ form.Demandlink.id_for_label }}" name="{{ form.Demandlink.name }}"
                               value="{{ form.Demandlink.value|default:'' }}">
                        {% if form.Demandlink.errors %}
                            <div class="invalid-feedback">
                                {{ form.Demandlink.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6">
                        <label for="{{ form.Testlink.id_for_label }}" class="form-label">测试链接</label>
                        <input type="url" class="form-control {% if form.Testlink.errors %}is-invalid{% endif %}"
                               id="{{ form.Testlink.id_for_label }}" name="{{ form.Testlink.name }}"
                               value="{{ form.Testlink.value|default:'' }}">
                        {% if form.Testlink.errors %}
                            <div class="invalid-feedback">
                                {{ form.Testlink.errors }}
                            </div>
                        {% endif %}
                    </div>
                </div>

                <h4 class="mt-4 mb-3 border-bottom pb-2">日期和进度</h4>

                <div class="row mb-3">
                    <div class="col-md-4">
                        <label for="{{ form.startdate.id_for_label }}" class="form-label">开始日期</label>
                        <input type="date" class="form-control {% if form.startdate.errors %}is-invalid{% endif %}"
                               id="{{ form.startdate.id_for_label }}" name="{{ form.startdate.name }}"
                               value="{{ form.startdate.value|date:'Y-m-d'|default:'' }}">
                        {% if form.startdate.errors %}
                            <div class="invalid-feedback">
                                {{ form.startdate.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-4">
                        <label for="{{ form.enddate.id_for_label }}" class="form-label">结束日期</label>
                        <input type="date" class="form-control {% if form.enddate.errors %}is-invalid{% endif %}"
                               id="{{ form.enddate.id_for_label }}" name="{{ form.enddate.name }}"
                               value="{{ form.enddate.value|date:'Y-m-d'|default:'' }}">
                        {% if form.enddate.errors %}
                            <div class="invalid-feedback">
                                {{ form.enddate.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-4">
                        <label for="{{ form.due_date.id_for_label }}" class="form-label">截止日期</label>

                        <input type="date" class="form-control {% if form.due_date.errors %}is-invalid{% endif %}"
                               id="{{ form.due_date.id_for_label }}" name="{{ form.due_date.name }}"
                               value="{{ form.due_date.value|date:'Y-m-d'|default:'' }}">
                        <span class="badge bg-info">钉钉提醒根据截止日期进行</span>
                        {% if form.due_date.errors %}
                            <div class="invalid-feedback">
                                {{ form.due_date.errors }}
                            </div>
                        {% endif %}
                    </div>
                </div>

                <div class="row mb-3">
                    <div class="col-md-6">
                        <label for="{{ form.testschedule.id_for_label }}" class="form-label">测试计划</label>
                        <input type="text" class="form-control {% if form.testschedule.errors %}is-invalid{% endif %}"
                               id="{{ form.testschedule.id_for_label }}" name="{{ form.testschedule.name }}"
                               value="{{ form.testschedule.value|default:'' }}">
                        {% if form.testschedule.errors %}
                            <div class="invalid-feedback">
                                {{ form.testschedule.errors }}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6">
                        <label for="{{ form.testprogress.id_for_label }}" class="form-label">测试进度</label>
                        <select class="form-select {% if form.testprogress.errors %}is-invalid{% endif %}"
                                id="{{ form.testprogress.id_for_label }}" name="{{ form.testprogress.name }}">
                            {% for value, text in form.testprogress.field.choices %}
                                <option value="{{ value }}"
                                        {% if form.testprogress.value == value %}selected{% endif %}>
                                    {{ text }}
                                </option>
                            {% endfor %}
                        </select>
                        {% if form.testprogress.errors %}
                            <div class="invalid-feedback">
                                {{ form.testprogress.errors }}
                            </div>
                        {% endif %}
                    </div>
                </div>

                <h4 class="mt-4 mb-3 border-bottom pb-2">图片信息</h4>

                <!-- 主图片上传 -->
                <div class="mb-3">
                    <label for="{{ form.Picturedata.id_for_label }}" class="form-label">主图片</label>
                    {% if form.instance.Picturedata %}
                        <div class="mb-2">
                            <!-- 使图片可点击，打开模态框 -->
                            <a href="#" data-bs-toggle="modal" data-bs-target="#imageModal">
                                <img src="{{ form.instance.Picturedata.url }}" alt="当前图片" class="img-thumbnail"
                                     style="max-height: 200px; cursor: pointer;">
                            </a>
                            <div class="mt-1">
                                <small class="text-muted">点击图片可查看大图</small>
                            </div>
                        </div>

                        <!-- 图片查看模态框 -->
                        <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel"
                             aria-hidden="true">
                            <div class="modal-dialog modal-xl">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="imageModalLabel">图片查看</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body text-center">
                                        <img src="{{ form.instance.Picturedata.url }}" alt="任务图片" class="img-fluid">
                                    </div>
                                    <div class="modal-footer">
                                        <a href="{{ form.instance.Picturedata.url }}" class="btn btn-primary"
                                           target="_blank">在新标签页中打开</a>
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    {% endif %}
                    <input type="file" class="form-control {% if form.Picturedata.errors %}is-invalid{% endif %}"
                           id="{{ form.Picturedata.id_for_label }}" name="{{ form.Picturedata.name }}">
                    <div class="form-text">上传新图片将替换当前主图片。如果不想更改图片，请留空。</div>
                    {% if form.Picturedata.errors %}
                        <div class="invalid-feedback">
                            {{ form.Picturedata.errors }}
                        </div>
                    {% endif %}
                </div>

                <!-- 额外图片上传 -->
                <div class="mb-3">
                    <label for="additional_images" class="form-label">额外图片</label>
                    <input type="file" class="form-control" id="additional_images" name="additional_images" multiple>
                    <div class="form-text">可以选择多张图片上传（按住Ctrl键可多选）</div>
                </div>

                <!-- 图片说明 -->
                <div class="mb-3">
                    <label for="{{ form.image_captions.id_for_label }}" class="form-label">图片说明</label>
                    <textarea class="form-control {% if form.image_captions.errors %}is-invalid{% endif %}"
                              id="{{ form.image_captions.id_for_label }}" name="{{ form.image_captions.name }}"
                              rows="3">{{ form.image_captions.value|default:'' }}</textarea>
                    <div class="form-text">每行一个说明，对应上传的图片顺序</div>
                    {% if form.image_captions.errors %}
                        <div class="invalid-feedback">
                            {{ form.image_captions.errors }}
                        </div>
                    {% endif %}
                </div>

                <!-- 显示现有额外图片 -->
                {% if existing_images %}
                    <div class="mb-4">
                        <h5>现有额外图片</h5>
                        <div class="row">
                            {% for image in existing_images %}
                                <div class="col-md-4 mb-3">
                                    <div class="card">
                                        <a href="#" data-bs-toggle="modal"
                                           data-bs-target="#extraImageModal{{ image.id }}">
                                            <img src="{{ image.image.url }}" class="card-img-top" alt="额外图片"
                                                 style="height: 150px; object-fit: cover; cursor: pointer;">
                                        </a>
                                        <div class="card-body">
                                            <p class="card-text">{{ image.caption|default:"无说明" }}</p>
                                            <form method="post" action="{% url 'delete-task-image' pk=image.id %}"
                                                  onsubmit="return confirm('确定要删除这张图片吗？');">
                                                {% csrf_token %}
                                                <button type="submit" class="btn btn-sm btn-danger">删除</button>
                                            </form>
                                        </div>
                                    </div>

                                    <!-- 额外图片查看模态框 -->
                                    <div class="modal fade" id="extraImageModal{{ image.id }}" tabindex="-1"
                                         aria-labelledby="extraImageModalLabel{{ image.id }}" aria-hidden="true">
                                        <div class="modal-dialog modal-xl">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="extraImageModalLabel{{ image.id }}">
                                                        图片查看</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                            aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body text-center">
                                                    <img src="{{ image.image.url }}" alt="任务图片" class="img-fluid">
                                                    {% if image.caption %}
                                                        <p class="mt-3">{{ image.caption }}</p>
                                                    {% endif %}
                                                </div>
                                                <div class="modal-footer">
                                                    <a href="{{ image.image.url }}" class="btn btn-primary"
                                                       target="_blank">在新标签页中打开</a>
                                                    <button type="button" class="btn btn-secondary"
                                                            data-bs-dismiss="modal">关闭
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                {% endif %}

                <h4 class="mt-4 mb-3 border-bottom pb-2">其他信息</h4>
                <div class="mb-3">
                    <label for="{{ form.Testingprocess.id_for_label }}" class="form-label">测试过程</label>
                    <textarea class="form-control  {% if form.Testingprocess.errors %}is-invalid{% endif %}"
                              id="{{ form.Testingprocess.id_for_label }}" name="{{ form.Testingprocess.name }}"


                              rows="3">{{ form.Testingprocess.value|default:'' }}</textarea>
                    {% if form.Testingprocess.errors %}
                        <div class="invalid-feedback">
                            {{ form.Testingprocess.errors }}
                        </div>
                    {% endif %}
                </div>

                <div class="mb-3">
                    <label for="{{ form.Remarks.id_for_label }}" class="form-label">备注</label>
                    <textarea class="form-control {% if form.Remarks.errors %}is-invalid{% endif %}"
                              id="{{ form.Remarks.id_for_label }}" name="{{ form.Remarks.name }}"
                              rows="3">{{ form.Remarks.value|default:'' }}</textarea>
                    {% if form.Remarks.errors %}
                        <div class="invalid-feedback">
                            {{ form.Remarks.errors }}
                        </div>
                    {% endif %}
                </div>

                <div class="mb-3 form-check">
                    {{ form.send_notification }}
                    <label class="form-check-label" for="{{ form.send_notification.id_for_label }}">
                        {{ form.send_notification.label }}
                    </label>
                    <div class="form-text">{{ form.send_notification.help_text }}</div>
                </div>

                <div class="d-flex justify-content-between mt-4">
                    <a href="{% url 'task-list' %}" class="btn btn-secondary">取消</a>
                    <button type="submit" class="btn btn-primary" id="saveButton">保存</button>
                </div>
            </form>
        </div>
    </div>

    {% block scripts %}
        <script>
            // 确保复选框可以正常切换
            document.addEventListener('DOMContentLoaded', function () {
                var notificationCheckbox = document.getElementById('{{ form.send_notification.id_for_label }}');
                if (notificationCheckbox) {
                    console.log('初始状态:', notificationCheckbox.checked);

                    // 监听复选框变化
                    notificationCheckbox.addEventListener('change', function () {
                        console.log('复选框状态变化为:', this.checked);
                    });
                }

                // 图片预览功能
                var additionalImagesInput = document.getElementById('additional_images');
                if (additionalImagesInput) {
                    additionalImagesInput.addEventListener('change', function () {
                        // 检查是否有预览容器，如果没有则创建
                        var previewContainer = document.getElementById('image-previews');
                        if (!previewContainer) {
                            previewContainer = document.createElement('div');
                            previewContainer.id = 'image-previews';
                            previewContainer.className = 'row mt-3';
                            this.parentNode.appendChild(previewContainer);
                        } else {
                            // 清空现有预览
                            previewContainer.innerHTML = '';
                        }

                        // 创建新的预览
                        if (this.files && this.files.length > 0) {
                            for (var i = 0; i < this.files.length; i++) {
                                var file = this.files[i];
                                if (file.type.match('image.*')) {
                                    var reader = new FileReader();
                                    reader.onload = (function (theFile, index) {
                                        return function (e) {
                                            var col = document.createElement('div');
                                            col.className = 'col-md-4 mb-3';

                                            var card = document.createElement('div');
                                            card.className = 'card';

                                            var img = document.createElement('img');
                                            img.src = e.target.result;
                                            img.className = 'card-img-top';
                                            img.alt = '预览图片 ' + (index + 1);
                                            img.style = 'height: 150px; object-fit: cover;';

                                            var cardBody = document.createElement('div');
                                            cardBody.className = 'card-body';

                                            var cardText = document.createElement('p');
                                            cardText.className = 'card-text';
                                            cardText.textContent = theFile.name;

                                            cardBody.appendChild(cardText);
                                            card.appendChild(img);
                                            card.appendChild(cardBody);
                                            col.appendChild(card);
                                            previewContainer.appendChild(col);
                                        };
                                    })(file, i);
                                    reader.readAsDataURL(file);
                                }
                            }
                        }
                    });
                }

                // 添加表单提交事件监听器
                var form = document.querySelector('form');
                var saveButton = document.getElementById('saveButton');

                if (form && saveButton) {
                    // 禁用表单的默认提交行为
                    form.addEventListener('submit', function (e) {
                        console.log('表单提交事件触发');
                    });

                    // 为保存按钮添加点击事件
                    saveButton.addEventListener('click', function (e) {
                        e.preventDefault();
                        console.log('保存按钮点击');

                        // 显示加载状态
                        saveButton.disabled = true;
                        saveButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';

                        // 提交表单
                        form.submit();
                    });
                }
            });

            // 获取项目经理
            function getProMan() {
                $.ajax({
                    url: "{% url 'get_info_from_api' %}",
                    type: "GET",
                    headers: {
                        'Content-Type': 'application/json',  // 如果需要发送数据的话
                        'X-Requested-With': 'XMLHttpRequest', // 或者其他自定义头部信息，取决于后端需求
                        'Access-Control-Allow-Origin': 'https://oa.yafex.cn'
                    },
                    success: function (data) {
                        const input_ele = document.querySelector('.pro-data')
                        {#input_ele.innerHTML = data#}
                        // 将data数据绑定到option元素上
                        for (let i = 0; i < data.length; i++) {
                            const option = document.createElement('option');
                            option.value = data[i].id;
                            option.text = data[i].name;
                            input_ele.appendChild(option);
                        }
                    }
                });

            }
        </script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    {% endblock %}
{% endblock %}